package com.example.zzzx;

import android.content.Intent;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    public static final int REQUEST_CODE_OVERLAY = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 检查是否具有悬浮窗权限
        if (checkOverlayPermission()) {
            // 启动悬浮窗服务
            startFloatingService();
        }
    }

    /**
     * 检查悬浮窗权限的方法
     */
    private boolean checkOverlayPermission() {
        // Android SDK23 对应的版本是 Android 6.0(Marshmallow)
        // 6.0 以上的 Android 系统需要动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            requestOverlayPermission();
            return false;
        }
        return true;
    }

    private void requestOverlayPermission() {
        // 弹出"请允许显示在其他应用上方 "的提示对话框
        new AlertDialog.Builder(this)
                .setTitle("需要悬浮窗权限")
                .setMessage("请允许显示在其他应用上方")
                .setPositiveButton("去设置", (dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, REQUEST_CODE_OVERLAY);
                })
                .setNegativeButton("取消", null)
                .show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 权限请求结束，返回该CODE，检查是否成功
        if (requestCode == REQUEST_CODE_OVERLAY) {
            if (checkOverlayPermission()) {
                startFloatingService();
            }
        }
    }

    private void startFloatingService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(new Intent(this, FloatingWindowService.class));
        } else {
            startService(new Intent(this, FloatingWindowService.class));
        }
    }

}